package com.youxin.chat.pay.service.channel;


import com.youxin.base.BaseResultCode;
import com.youxin.chat.pay.config.PayProperties;
import com.youxin.chat.pay.dto.PayRulesDto;
import com.youxin.chat.pay.mapper.ChannelAccountMapper;
import com.youxin.chat.pay.model.ChannelAccount;
import com.youxin.chat.pay.service.PayRulesService;
import com.youxin.chat.pay.service.manager.ChannelManager;
import com.youxin.exception.SystemException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class ChannelRouter {

    @Resource
    private List<IPayChannel> payChannelList;

    @Resource
    private ChannelAccountMapper channelAccountMapper;

    @Resource
    private ChannelManager channelManager;

    @Resource
    private PayRulesService payRulesService;

    @Resource
    private PayProperties payProperties;

    public ChannelAccount getDefaultChannelAcccount(){
        PayRulesDto payRulesDto = payRulesService.info();
        String accountNo = Optional.ofNullable(payRulesDto.getChannelAccount()).orElse(payProperties.getChannel().getPayAccount());
        ChannelAccount channelAccount = channelManager.getChannelByAccount(accountNo);
        if(channelAccount == null){
            throw new SystemException(BaseResultCode.COMMON_FAIL,"渠道未配置");
        }
        return channelAccount;
    }

    public ChannelAccount getChannelAcccountByAccountNo(String accountNo){
        ChannelAccount channelAccount = channelManager.getChannelByAccount(accountNo);
        if(channelAccount == null){
            throw new SystemException(BaseResultCode.COMMON_FAIL,"渠道未配置");
        }
        return channelAccount;
    }

    public IPayChannel getPayChannel(ChannelAccount channelAccount){
        for(IPayChannel payChannel: payChannelList){
            if(payChannel.support(channelAccount.getChannelCode())){
                return payChannel;
            }
        }
        throw new SystemException(BaseResultCode.COMMON_FAIL,"渠道未配置");
    }
}
